package com.cooge.colletion.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.cooge.colletion.model.Content;
import com.cooge.colletion.model.Rx;

public class HtmlUtil {

	public static Elements HtmlDownload(String url, String tag) {

		 
		Document doc = null;
		try {
			doc = Jsoup.connect(url).get();
		} catch (IOException e) {

			e.printStackTrace();
		}
		String s[] = tag.split(" ");
		Elements eles = DomUtil.Domanalysis(doc, s);
		return eles;
	}

	public static List<Content> getContent(String page,String title,Rx rx) {
		
		String url =rxToUrl(rx).replace("[T]",title).replace("[t]",title).replace("[P]", page).replace("[p]", page).replace("\r","");
		
		
		System.out.println(url);
		
		List<Content> clist = new ArrayList<Content>();
		Document doc = null;
		try {
			doc = Jsoup.connect(url).get();
		} catch (IOException e) {

			e.printStackTrace();
		}
		
		Elements  eles =DomUtil.Domanalysis(doc, rx.getProgramaTag().split(" "));
		
		
		Iterator<Element>  ie= eles.iterator();
		
		while(ie.hasNext()){
			
			Element e = 	ie.next();
			Content  cc = new Content();
			
			String img = DomUtil.Domanalysis(e, rx.getImgTag().split(" ")).attr("src");
			cc.setImg(img);
			String tit = DomUtil.Domanalysis(e, rx.getTitleTag().split(" ")).html();
			
			cc.setTitle(tit);
			
			String text = DomUtil.Domanalysis(e, rx.getTextTag().split(" ")).html();
			
			cc.setText(text);
			clist.add(cc);
			System.out.println(cc.toString());
			
			
		}
		
		
		

		return clist;
	}

	public static String rxToUrl(Rx rx) {

		String rule = rx.getRule();

		return rule.replace("[W]", rx.getRxUrl()).replace("[w]",  rx.getRxUrl());
	}
	
	

}
